import json
import os
from datetime import datetime
from dateutil.relativedelta import relativedelta

import pyautogui as pag


def get_current_position():
    print("press ctrl-C to quit.")  # Press Ctrl+F8 to toggle the breakpoint.
    try:
        while True:
            x, y = pag.position()
            positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
            print(positionStr, end='')
            print('\b' * len(positionStr), end='', flush=True)
    except KeyboardInterrupt:
        print('\n')


def get_config(file):
    with open(file, 'r') as f:
        return json.load(f)


def getEnvPath():
    realpath = os.path.dirname(__file__)
    return realpath


def do(config, year, month, day):
    # 刷新
    pag.click(x=config["refresh"]['x'], y=config["refresh"]['y'])
    pag.sleep(5)
    # 购买
    pag.click(x=config["buy1"]['x'], y=config["buy1"]['y'])
    pag.sleep(1)
    # 购物车
    pag.click(x=config["buyCar"]['x'], y=config["buyCar"]['y'])
    pag.sleep(1)
    # 更改数量为2
    pag.doubleClick(x=config["changeNumber"]['x'], y=config["changeNumber"]['y'])
    pag.typewrite('2')
    pag.sleep(1)
    # 选中
    pag.click(x=config["select"]['x'], y=config["select"]['y'])
    pag.sleep(1)
    # 提交订单
    pag.click(x=config["submit"]['x'], y=config["submit"]['y'])
    pag.sleep(1)
    # 更改地址
    pag.click(x=config["changeAddress"]['x'], y=config["changeAddress"]['y'])
    pag.sleep(1)
    pag.click(x=config["selectAddress"]['x'], y=config["selectAddress"]['y'])
    pag.sleep(1)
    # 更改日期
    pag.doubleClick(x=config["changeTime"]['x'], y=config["changeTime"]['y'])
    pag.typewrite(str(year))
    pag.typewrite(str(month))
    pag.typewrite(str(day))
    pag.sleep(1)
    # 前往支付
    pag.click(x=config["toPay"]['x'], y=config["toPay"]['y'])
    pag.sleep(1)
    # 确认
    pag.click(x=config["ok"]['x'], y=config["ok"]['y'])
    pag.sleep(1)
    # 返回第一次
    pag.click(x=config["back"]['x'], y=config["back"]['y'])
    pag.sleep(1)
    # 返回第二次
    pag.click(x=config["back"]['x'], y=config["back"]['y'])
    pag.sleep(1)


if __name__ == '__main__':
    # 等待5s用户准备
    pag.sleep(5)
    config = get_config("C:\config.json")
    date = datetime.now() + relativedelta(months=+1)
    day = date.day
    month = date.month
    year = date.year
    while True:
        do(config=config, year=year, month=month, day=day)
